<template>
  <div id="login">
    欢迎登录
    <!-- <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"> -->
    <!-- model vue里边的双向绑定 ref 获取from 这个dom对象 -->
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules"
             label-width="80px" class="demo-ruleForm">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
        <!-- <el-button @click="resetForm('ruleFormRef')">重置</el-button> -->
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  // name: 'app',
  data () {
    return {
      ruleForm: {
        username: 'admin',
        password: '123456',
      },
      // 校验规则,:rules来绑定
      rules: {
        /* 有多个的校验规则,对象 */
        username: [
          /* 必填项trigger触发校验规则的条件 blur,change,改变的时候,focus获取焦点
          type 填写信息的类型,date,email,number,url
          */
          { required: true, message: '必填的,可以写别的', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        password: [
          /* 必填项trigger触发校验规则的条件 */
          { required: true, message: '必填的,可以写别的', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          // { type: 'number', required: true, message: '请填写数字类型', trigger: 'blur' },
        ]
      }
    }
  },
  methods: {
    // async,await 简化访问的操作,将异步的操作顺序化
    login () {
      // validate 自带校验方法,获取到当前elform对象valid 会返回
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (valid) {
          // es6的高级解构
          const back = await this.$axios.post('login', this.ruleForm)
          console.log(back)
          if (back.data.meta.status === 200) {
            this.$message({
              message: back.data.meta.msg,
              type: 'success'
            });
            // 登录的证明,唯一的把登录的凭证保存到页面内
            window.sessionStorage.setItem("token", back.data.data.token)
            // 跳转到home页面
            this.$router.push('/home')
          } else {
            this.$message({
              message: back.data.meta.msg,
              type: 'error'
            });
          }
        } else {
          this.$message('校验没通过')
        }
      });
    },
    reset: function () {
      console.log(this.$refs)
      this.$refs.ruleFormRef.resetFields()
    },
  },
}
</script>
<style lang="css" scoped>
#login {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
  margin: 100px auto;
  width: 30%;
}
</style>
